﻿/*
 * Сделано в SharpDevelop.
 * Пользователь: max
 * Дата: 08/31/2012
 * Время: 20:06
 * 
 * Для изменения этого шаблона используйте Сервис | Настройка | Кодирование | Правка стандартных заголовков.
 */
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.ComponentModel;
using jellybird.core;

namespace jellybird
{
	/// <summary>
	/// Interaction logic for Window1.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		public MainWindow()
		{
			InitializeComponent();
			
//			CommandManager.InvalidateRequerySuggested();
			
//			prepare_timelines();
			
//			later_init();

			//TwMediaHelper.RetrieveThumbnail(@"http://twitpic.com/qwertyu", 360);
//			Uri test_uri=new Uri(@"http://instagr.am/p/Qmi5SDg_LR/",UriKind.Absolute);
//			string[] segs=test_uri.Segments;

//			TwMediaHelper.GetMediaInfoTwitpic("1fdn1r");
			//TwMediaHelper.GetMediaInfoYfrog("g09v2zkj");
			//TwMediaHelper.GetMediaInfoYoutube("yhLiqCdFyQs");
		}
		
//		private TwAccount m_account;
		private CollectionViewSource view_source;
		
		private void later_init()
		{
			#if DEBUG
			Program.JellybirdApplication.DebugMessage
				("Find collection view source.");
			#endif
			view_source=(CollectionViewSource)FindResource("ReadedTweetsView");
			
			
			#if DEBUG
			Program.JellybirdApplication.DebugMessage
				("Add account change handlers.");
			#endif
			//обработчик, чтобы добавленный эккаунт сразу выбирался в комбо
			Program.AccountManager.CollectionChanged+=
				(s,e)=>
			{
				if(e.Action==System.Collections.Specialized.NotifyCollectionChangedAction.Add)
				{
					if((e.NewItems!=null)&&(e.NewItems.Count>0))
						combo_AccountSelector.SelectedItem=e.NewItems[0];
				}
			};
			
			//обработчик, чтобы при выборе эккаунта подключалась
			//соответствующая лента
			combo_AccountSelector.SelectionChanged+=
				(s,e)=>
			{
				if((e.AddedItems!=null)&&(e.AddedItems.Count>0))
				{
					bind_timeline((TwAccount)e.AddedItems[0]);
				}
			};
			
			#if DEBUG
			Program.JellybirdApplication.DebugMessage
				("Set account selector initial state");
			#endif
			//в этот момент уже имеем загруженный из файла Program.AccountManager
			//и привязанный к нему combo_AccountSelector
			//если в AccountManager есть эккаунты, выберем в AccountSeletor'е первый например
			//или иной, но это надо будет сохранять тогда
			if(Program.AccountManager.Count>0)
			{
				combo_AccountSelector.SelectedIndex=0;
			}
			else
			{
				//а если сохранённых эккаунтов нет
				//предлагаем добавить эккаунт
				MyCommands.AddAccountCommand.Execute(null,this);
			}
		}
		
		private void bind_timeline(TwAccount selected_account)
		{
			#if DEBUG
			Program.JellybirdApplication.DebugMessage
				("Rebind timeline.");
			#endif
			
			if(selected_account==null)
				return;
			
			
			if((DataContext==null)||(DataContext!=selected_account))
			{
				#if DEBUG
				Program.JellybirdApplication.DebugMessage
					("Set DataContext.");
				#endif
				DataContext=selected_account;
			}
			
			//какая радиокнопка нажата?
			if((toggle_HomeTimeline.IsChecked.HasValue)&&(toggle_HomeTimeline.IsChecked.Value))
			{
				view_source.Source=selected_account.HomeTimeline;
				selected_account.Current=selected_account.HomeTimeline;
			}
			else if((toggle_MentionsTimeline.IsChecked.HasValue)&&(toggle_MentionsTimeline.IsChecked.Value))
			{
				view_source.Source=selected_account.MentionsTimeline;
				selected_account.Current=selected_account.MentionsTimeline;
			}
			else if((toggle_MyTweets.IsChecked.HasValue)&&(toggle_MyTweets.IsChecked.Value))
			{
				view_source.Source=selected_account.UserTimeline;
				selected_account.Current=selected_account.UserTimeline;
			}
			
			//Зададим начальные свойства
			if(!selected_account.Current.ClientFlag)
			{
				#if DEBUG
				Program.JellybirdApplication.DebugMessage
					("Set initial timeline params.");
				#endif
				selected_account.Current.AutoUpdatePeriod=app.Default.AutoUpdatePeriod;
				selected_account.Current.EnableAutoUpdate=app.Default.AutoUpdateTimelines;
				selected_account.Current.MaxEntriesPerUpdate=app.Default.TweetCount;
				selected_account.Current.ContributorDetails=true;
				selected_account.Current.IncludeRts=true;
				
				if(app.Default.LoadTweetsAfterStart)
				{
					#if DEBUG
					Program.JellybirdApplication.DebugMessage
						("Begin initial update.");
					#endif
					selected_account.Current.BeginUpdate(null,null,null);
				}
				
				selected_account.Current.ClientFlag=true;
			}
			
		}
		
		private void bind_timeline()
		{
			if(combo_AccountSelector.SelectedItem!=null)
			{
				TwAccount selected_acc=(TwAccount)combo_AccountSelector.SelectedItem;
				bind_timeline(selected_acc);
			}
		}
		
		
		void Command_Credentials_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			Program.JellybirdApplication.DebugMessage("Command <Credentials> invoked");
			
			
			TwCredentials Credentials=new TwCredentials();
			
			ChildWindowCredentials.DataContext = Credentials;
			ChildWindowCredentials.Show();
		}
		
		void toggleButton1_Checked(object sender, RoutedEventArgs e)
		{
			
		}
		
		void button1_Click(object sender, RoutedEventArgs e)
		{
			if (ListBoxTweets.ItemsSource != null)
			{
				TwTimeline timeline =
					(ListBoxTweets.ItemsSource as CollectionView).SourceCollection as TwTimeline;
				if (timeline != null)
				{
					if (timeline.MaxKey == -1)
						timeline.BeginUpdate();
					else
						timeline.BeginUpdate(timeline.MaxKey-1L);
				}
			}
		}
		
		void button2_Click(object sender, RoutedEventArgs e)
		{
//			Binding binding=BindingOperations.GetBinding(ListBoxTweets,ListBox.ItemsSourceProperty);
//			TwTimeline timeline=binding.Source as TwTimeline;
//			if(timeline!=null)
//			{
//				timeline.Clear();
//			}
			
			
//			ChildWindowTest.DataContext=Program.SettingsStore;
//			ChildWindowTest.Show();
			
			
		}
		
		
		
		void ToggleHomeTimeline_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			bind_timeline();
//			CollectionViewSource view_source=FindResource("ReadedTweetsView") as CollectionViewSource;
//			m_account.Current=m_account.HomeTimeline;
//			view_source.Source=m_account.HomeTimeline as IList<TwTweet>;
			
			
//			BindingOperations.ClearBinding(ListBoxTweets,ListBox.ItemsSourceProperty);
//
//			Binding binding=new Binding()
//			{
//				Mode= BindingMode.OneWay,
//				Path=new PropertyPath("HomeTimeline")
//			};
//			BindingExpressionBase res=ListBoxTweets.SetBinding(ListBox.ItemsSourceProperty,binding);
		}
		
		void ToggleMentionsTimeline_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			bind_timeline();
//			CollectionViewSource view_source=FindResource("ReadedTweetsView") as CollectionViewSource;
//			m_account.Current=m_account.MentionsTimeline;
//			view_source.Source=m_account.MentionsTimeline;
			
//			BindingOperations.ClearBinding(ListBoxTweets,ListBox.ItemsSourceProperty);
//
//			Binding binding=new Binding()
//			{
//				Mode= BindingMode.OneWay,
//				Path=new PropertyPath("MentionsTimeline")
//			};
//			ListBoxTweets.SetBinding(ListBox.ItemsSourceProperty,binding);
		}
		
		void ToggleUserTimeline_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			bind_timeline();
//			CollectionViewSource view_source=FindResource("ReadedTweetsView") as CollectionViewSource;
//			m_account.Current=m_account.UserTimeline;
//			view_source.Source=m_account.UserTimeline;
			
//			BindingOperations.ClearBinding(ListBoxTweets,ListBox.ItemsSourceProperty);
//
//			Binding binding=new Binding()
//			{
//				Mode= BindingMode.OneWay,
//				Path=new PropertyPath("UserTimeline")
//			};
//			ListBoxTweets.SetBinding(ListBox.ItemsSourceProperty,binding);
		}
		
		void Filter_ExcludeUnreaded(object sender, FilterEventArgs e)
		{
			TwTweet t=e.Item as TwTweet;
			TwTimeline timeline=(TwTimeline)((CollectionViewSource)sender).Source;
			TwTweet first_readed=timeline.FirstReadedTweet;
			if(first_readed==null)
			{
				e.Accepted=true;
			}
			else
			{
				e.Accepted=t.Id<=first_readed.Id;
			}
		}
		
		void MainWindowName_Closing(object sender, CancelEventArgs e)
		{
			
		}
		
		void UnreadedButton_Click(object sender, RoutedEventArgs e)
		{
			if(combo_AccountSelector.SelectedItem!=null)
			{
				TwAccount selected_acc=(TwAccount)combo_AccountSelector.SelectedItem;
				
				if((selected_acc!=null)&&(selected_acc.Current!=null))
				{
					selected_acc.Current.FirstReadedTweet=null;
					selected_acc.Current.ForceReset();
					ListBoxTweets.SetFirstVisibleItem(selected_acc.Current[0]);
				}
			}
		}
		
		void AddAccount_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			MyHandlers.AddAccountDialogStart(sender,e);
		}
		
		void OkDialogCredentialsExecuted(object sender, ExecutedRoutedEventArgs e)
		{
			((Xceed.Wpf.Toolkit.ChildWindow)sender).Close();
			MyHandlers.CredentialsDialogReturns(sender,e);
		}
		
		void CancelDialog_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			((Xceed.Wpf.Toolkit.ChildWindow)sender).Close();
		}
		
		void MainWindow_Loaded(object sender, RoutedEventArgs e)
		{
			later_init();
		}
		
		void ProcessGap_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			#if DEBUG
			Program.JellybirdApplication.DebugMessage("Gap command executed");
			#endif
			
			if (ListBoxTweets.ItemsSource != null)
			{
				TwTimeline timeline =
					(ListBoxTweets.ItemsSource as CollectionView).SourceCollection as TwTimeline;
				if (timeline != null)
				{
					//получили ссылку на TwTimeline
					//ссылка на твит перед разрывом - в параметре
					TwTweet tweet_gap=e.Parameter as TwTweet;
					if(tweet_gap!=null)
					{
						//обновляем ленту ДО tweet_gap и после предыдущего твита
						TwTweet tweet_pre=null;
						int ind_of_gap=timeline.IndexOf(tweet_gap);
						if(ind_of_gap<timeline.Count-1)
						{
							//то есть если tweet_gap не последний в коллекции
							tweet_pre=timeline[ind_of_gap+1];
						}
						//отнимаем единицу, чтобы не вернулся этот же твит ещё раз
						long? max_id=tweet_gap.Id-1L;
						long? since_id=tweet_pre==null?null:(long?)tweet_pre.Id;
						timeline.BeginUpdate(since_id,max_id);
						//очистим атрибут GapDetected у этого твита,
						//потому что перед ним разрыва точно не должно быть
						tweet_gap.GapDetected=false;
					}
				}
			}
		}
		
		
	}
}